package com.iot.modbus.factory;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.ip.IpParameters;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionFactory {

    public static final ModbusFactory modbusFactory = new ModbusFactory();
    private static final Map<String, ModbusMaster> modbusMasterMap = new ConcurrentHashMap<>();

    private static String getKey(final IpParameters ipParameters) {
        return ipParameters.getHost() + "<>" + ipParameters.getPort();
    }

    public static ModbusMaster add(IpParameters ipParameters) {
        ModbusMaster modbusMaster = modbusFactory.createTcpMaster(ipParameters,true);;
        modbusMasterMap.put(getKey(ipParameters), modbusMaster);
        return modbusMaster;
    }

    public static ModbusMaster remove(IpParameters ipParameters) {
        return modbusMasterMap.remove(getKey(ipParameters));
    }

    public static ModbusMaster get(IpParameters ipParameters) {
        if (!modbusMasterMap.containsKey(getKey(ipParameters))) {
            return add(ipParameters);
        }
        return modbusMasterMap.get(getKey(ipParameters));
    }
}
